<?php
namespace jy_aixiaoyi;
defined('BY_JYA') or exit('error');
/*
	分销佣金
	
*/
class commission extends \plugin{
    
    
	/*
		生成佣金
	*/
	function create($order,$ctype=2){
	    
		$this->order=$order;
		$member=$this->get('member',array('mid'=>$order['mid']),array('mid','is_agent','agent_id','level_id'));
		$agent_id = $member['agent_id'];
		if(!$agent_id){
			return false;
		}
	    //此处没有问题
		if($member['level_id']){
			$nowlevel=$this->getcolumn('level',array('id'=>$member['level_id']),'level');
		}else{
			$nowlevel=0;
		}
		if($this->order['price']<=0){
			return false;
		}
		//现在支付方式分佣
		if($this->setting['pay_type']){
			$paylog=pdo_get('core_paylog',array('id'=>$order['pay_id']),array('pay_type','di_credit','di_fee','fee'));
			if($paylog['di_fee']>0){
				if(strpos($this->setting['pay_type'],';'.$paylog['di_credit'].';') !== false){
					$this->order['price'] -= $paylog['di_fee'];
				}
				if(strpos($this->setting['pay_type'],';'.$order['paytype'].';') !== false){
					$this->order['price'] -= $paylog['fee']-$paylog['di_fee'];
				}
				//两种支付都不支持
				if(strpos($this->setting['pay_type'],';'.$paylog['di_credit'].';') !== false && strpos($this->setting['pay_type'],';'.$order['paytype'].';') !== false){
					return;
				}
			}elseif(strpos($this->setting['pay_type'],';'.$order['paytype'].';') !== false){
				return;
			}
		}
		
		if($member['agent_id']){
			$this->commission_order=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$this->order['mid'],
				'ordersn'=>$this->order['ordersn'],
				'order_price'=>$this->order['price'],
				'plugin_name'=>$this->order['plugin_name']?:'',
				'commission_money'=>0,
				'xuni_money'=>0,
				'jifen'=>0,
				'createtime'=>TIMESTAMP,
			);
		}
		//佣金计算方式 通过商品进行计算
		$this->commission_order['commission_price']=$this->order['price'];
		$this->commission_order['ordersn'] = $this->order['ordersn'];
		if($member['agent_id']){
			$agent=$this->get('member',array('mid'=>$agent_id));
			//推广佣金(购买指定商品)
			if($ctype==1){
			    $this->create_commission($agent,1,1);
			}else{
			    $this->create_commission($agent,17,2);
			}
		}
		//生成分销订单
		$indata=$this->commission_order;
		$this->insert('order',$indata);
		return true;
	}
	/*
	 ***推广佣金(购买指定商品)
	*/
	function create_commission($member,$type=1,$ctype=1){
		if($member && $member['is_agent'] && $member['stop']==0){
		   
			$level=$this->get('level',array('id'=>$member['level_id'],'uniacid'=>$_SESSION['uniacid']));
		
			$level_id=$level['id'];
			$commission_per=$level['fee_per'];
			$commission_per1=$level['fee_per1'];
		
			$money=0;
			$order_price=$this->commission_order['commission_price'];
			//此处判断分销商是否满足升级条件，如果满足则升级分销商等级
			if($ctype==1 && $commission_per){
			    //推广佣金(购买指定商品)
			    if($order_price>0){
    				if(substr($commission_per,-1)=='%'){
    					$order_commission_money=($order_price*substr($commission_per,0,-1))/100;
    				}else{
    					$order_commission_money=$commission_per;
    				}
    				$money+=$order_commission_money;  
			    }
			}
			if($ctype==2 && $commission_per1){
			    //推广人头激活费
    			$order_commission_money=$commission_per1;
    			$money+=$order_commission_money;  
			}
			//平台发放
			if($money>0 && $type==1){
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$member['mid'],
					'type'=>$type,
					'level'=>1,
					'ordersn'=>$this->commission_order['ordersn'],
					'money'=>$money,
					'createtime'=>TIMESTAMP,
					'isxuni'=>0,
					'status'=>$this->setting['is_jiesuan']?1:0,
					'pluginname'=>'jy_aixiaoyi'
				);
			}
			if($money>0 && $type==17){
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$member['mid'],
					'type'=>$type,
					'level'=>1,
					'ordersn'=>$this->commission_order['ordersn'],
					'money'=>$money,
					'createtime'=>TIMESTAMP,
					'isxuni'=>0,
					'status'=>$this->setting['is_jiesuan']?1:0,
					'pluginname'=>'jy_aixiaoyi'
				);
				//激活增送知识币
				$this->up_xunifee($order,$member['mid']);
			}
			$this->insert('commission',$new_commission);
			$member_update=array(
				'order_price'=>$member['order_price'] + $this->commission_order['order_price'],
				'order_num'=>$member['order_num']+1,
			);
			$this->update('member',$member_update,array('mid'=>$member['mid']));
		}
		//如果他的上级是我
		$ta_agent_id=$this->getcolumn('member',array('mid'=>$member['agent_id']),'agent_id');
		if($ta_agent_id==$agent_id){
			return false;
		}
		return $member['agent_id'];
	}
	/*
	***虚拟币(知识币)
	*/
	public function up_xunifee($order,$agent_id){
		if(!$agent_id){
			return false;
		}
		if($this->setting['xuni_open']!=1){
			return false;
		}
		$order_price=$order['price'];
		$money=0;
		$member=$this->get('member',array('mid'=>$agent_id));

		if($member['level_id']){
			$level=$this->get('level',array('id'=>$member['level_id'],'uniacid'=>$_SESSION['uniacid']));
			$money +=$level['jindoufee'];
		}
		if($money>0){
		 
			model('core/member')->member_credit($agent_id,'credit3',$money,true,'jy_aixiaoyi','用户激活码激活获取金币','bi_tuiguang'.$agent_id);
		}
	}
	/*
	***订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
	    
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('ordersn'=>$order['ordersn'],'status'=>0));
		
	}
	/*
	***创建结算单
	*/
	public function create_balance($mid,$post=array()){
	 
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if($post['pay_type']=='downline'){
			if(!$post['wechat']){
				exi('请先填写微信号！','error');
			}
			if(!$post['mobile']){
				exi('请先填写联系电话！','error');
			}
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
			$typetitle='支付宝';
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='银行卡';
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1,'isxuni'=>0);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$money=pdo_getsum('jy_aixiaoyi_commission',$params,'money');
		if($money<=0){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=$this->count('commission',$params,'id');
		//结算最低佣金检测
		if($money<$this->setting['balance_fee']){
			exi('可结算佣金太少，无法结算！','error');
		}
	    //佣金的上限  300  100
	    if($money<$this->setting['balance_money_start']){
			exi('提现金额太低,请提高额度！','error');
		}
	    //佣金的下限
	    if($money>$this->setting['balance_money_end']){
			exi('提现金额超过上限,请降低额度！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'wechat'=>$post['wechat'],
			'mobile'=>$post['mobile'],
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		$update=array(
			'status'=>2,
			'balancesn'=>$new_balance['balancesn'],
		);
		$this->update('commission',$update,$params);
		if($post['pay_type']=='credit'){
			$typetitle='余额';
		}
		if($post['pay_type']=='wechat'){
			$typetitle='微信';
		}
		return $balance_id;
	}
	/*
	***审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
		return true;
		/*$update=array(
			'status'=>1,
			'balancesn'=>'',
		);
		$balance=$this->get('balance',array('id'=>$balance_id),array('mid','balancesn'));
		if($balance['balancesn']){
			$this->update('commission',$update,array('uniacid'=>$_SESSION['uniacid'],'mid'=>$balance['mid'],'balancesn'=>$balance['balancesn']));
		}*/
		return true;
	}
	/*
	***打款结算单
	*/
	public function pay_balance($balance_id,$pay_type='',$wxgid='',$pay_trade_no=''){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			//exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$wxgid);
		$update=array(
			'status'=>3,
			'pay_trade_no'=>$trade_no=='pay_trade_no'?$pay_trade_no:$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		if($pay_type){
			$update['pay_type']=$pay_type;
		}
		$this->update('balance',$update,array('id'=>$balance['id']));
		return true;
	}
	/*
	***线下打款
	*/
	protected function pay_balance_by_downline(){
		return 'pay_trade_no';
	}
	/*
	***打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,'jy_commission','分销佣金打款');
	}
	/*
	***打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$wxgid=''){
		if($wxgid){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxgid,'uniacid'=>$_SESSION['uniacid']),array('appid','mchid','paykey'));
		}
		$params=array(
			'appid'=>$wxapp['appid']?:'',
			'mch_id'=>$wxapp['mchid']?:'',
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'wxgid'=>$wxgid,
			'remark'=>'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		if(!$res['payment_no'] && !$res['batch_id']){
			exi('打款到微信零钱失败！','error');
		}
		return $res['payment_no']?:$res['batch_id'];
	}
	/*
	***打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到支付宝！','error');
	}
	/*
	***打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，佣金规则【{$goods['commission_per']}】，分销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='未启用';
		}
		$remark['level_title']=pdo_getcolumn('jy_commission_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['commission_level']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
分销商等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，佣金等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立佣金：
{$goods_str}
订单佣金：
除去设置独立佣金的商品外订单金额【{$remark['order_commission']['order_price']}】，佣金规则【{$remark['order_commission']['commission_per']}%】，分销佣金【{$remark['order_commission']['commission_money']}】
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
	/*
	***获取单独商品佣金
	*/
	protected function get_goodsfee($goodsid,$orderid,$ordergoodsid=''){
		$ordersn=pdo_getcolumn('jy_weishop_order',array('id'=>$orderid,'uniacid'=>$_SESSION['uniacid']),'ordersn');
		$commissionremark=$this->pdo_getcolumn('commission',array('ordersn'=>$ordersn,'uniacid'=>$_SESSION['uniacid']),'remark');
		//print_r($ordersn.'~~'.$commissionremark);exit;
		$commissionremark=json_decode($commissionremark,true);
		
		$goodsfee=0;
		if($commissionremark['goods_commission']){
			foreach($commissionremark['goods_commission'] as $gv){
				if($ordergoodsid){
					if($ordergoodsid==$gv['ordergoodsid']){
						$goodsfee +=$gv['commission_money'];
					}
				}else{
					if($goodsid==$gv['goods_id']){
						$goodsfee +=$gv['commission_money'];
					}
				}
			}
		}
		if($commissionremark['order_commission'] && $goodsfee==0){
			$allorderfee=pdo_getsum('jy_weishop_order_goods',array('orderid'=>$orderid,'goodsid'=>$goodsid),'total_price');
			//exi($allorderfee.'~'.$commissionremark['order_commission']['order_price'].'~'.$commissionremark['order_commission']['commission_money'],'error');
			$goodsfee=($allorderfee/$commissionremark['order_commission']['order_price'])*$commissionremark['order_commission']['commission_money'];
		}
		return $goodsfee;
	}
}